﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.IO;

namespace SharpShare.Storage.FileSystem {
    internal class FolderLookup : IStorageLookup {
        private int? _count;

        public FolderLookup(string path, IFileStorageItemFactory factory) {
            this.Path = path;
            this.Factory = factory;
        }

        public string Path { get; private set; }
        public IFileStorageItemFactory Factory { get; private set; }

        private string[] Subpaths {
            get {
                try {
                    return System.IO.Directory.GetFileSystemEntries(this.Path);
                } catch (Exception ex) {
                    throw FileStorageItem.HandleException(ex);
                }
            }
        }

        #region IStorageLookup Members

        public int Count {
            get {
                return 1;

                if (!_count.HasValue) {
                    _count = this.Subpaths.Length;
                }

                return _count.Value;
            }
        }

        public IStorageItem this[string name] {
            get {
                string path = PathUtils.Combine(this.Path, PathUtils.EscapeFilename(name));
                if (!System.IO.Directory.Exists(path) && !System.IO.File.Exists(path)) {
                    return null;
                }

                return this.Factory.Create(path);
            }
        }

        #endregion

        private IEnumerable<IStorageItem> ListContents() {
            foreach (string path in this.Subpaths) {
                try {
                    FileAttributes attrs = System.IO.File.GetAttributes(path);

                    if (attrs.HasFlag(FileAttributes.System)) {
                        continue;
                    }
                } catch (Exception) {
                    continue;
                }

                FileStorageItem item = this.Factory.Create(path);
                if (item != null) {
                    yield return item;
                }
            }
        }

        #region IEnumerable<IStorageItem> Members

        public IEnumerator<IStorageItem> GetEnumerator() {
            return ListContents().GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }

        #endregion

    }
}
